// js
Page({
  data: {
    rotate: 0,
    rotateX: 0,
    rotateY: 0,
    startX: 0,
    startY: 0,
    data: null,
    uniqueTypes: []
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id }, () => {
        this.loadData()
      })
    }
  },
  async loadData() {
    wx.showLoading({ title: '加载中...' })
    try {
      const res = await wx.cloud.callFunction({
        name: 'getPoiData',
        data: { id: this.data.id }
      })
  
      if (res.result.code === 200) {
          const data = res.result.data || {}
          const rawType = data.type || '未分类;'
          
          const types = rawType
            .split(';')
            .map(t => t.trim())
            .filter(t => t.length > 0)
          
          this.setData({
            data: data,
            uniqueTypes: [...new Set(types)]
          })
        
      } else {
        wx.showToast({ icon: 'none', title: res.result.message || '数据获取失败' })
      }
    } catch (err) {
      console.error('数据加载失败：', err)
      wx.showToast({ icon: 'none', title: '数据加载失败' })
    } finally {
      wx.hideLoading()
    }
  },

  openLocation() {
    if (this.data.data && this.data.data.location) {
      wx.openLocation({
        latitude: this.data.data.location[1],
        longitude: this.data.data.location[0],
        name: this.data.data.name,
        address: this.data.data.address,
      })
    }
  },
  

  handleTouchStart(e) {
    this.setData({
      startX: e.touches[0].clientX,
      startY: e.touches[0].clientY
    });
  },

  handleTouchMove(e) {
    const currentX = e.touches[0].clientX;
    const currentY = e.touches[0].clientY;
    const deltaX = currentX - this.data.startX;
    const deltaY = currentY - this.data.startY;
    
    // 计算旋转角度和方向
    const maxRotate = 60; // 最大旋转角度
    const sensitivity = 0.3; // 旋转灵敏度
    
    const rotateX = deltaY * sensitivity / 100;
    const rotateY = deltaX * sensitivity / 100;
    const rotate = Math.min(
      Math.sqrt(deltaX * deltaX + deltaY * deltaY) * sensitivity,
      maxRotate
    );

    this.setData({
      rotate: rotate,
      rotateX: rotateX,
      rotateY: rotateY
    });
  },

  handleTouchEnd() {
    this.setData({
      rotate: 0,
      rotateX: 0,
      rotateY: 0
    });
  },

   // 新增关注处理函数
   async handleFollow() {
    if (!this.data.data) return
    
    // 优先检查本地登录状态
      const localUser = wx.getStorageSync('userinfo')
      if (!localUser?.nickName) {
        wx.showToast({
          title: '🌟 请登录后继续操作',
          icon: 'none',
          duration: 1000,
          mask: true
        });
        // 第二步：异步提示流程
        setTimeout(() => {
          // 触觉反馈
          wx.vibrateShort({ type: 'heavy' });

          // 第三步：跳转预加载提示
          wx.showLoading({
            title: '正在前往登录页...',
            mask: true
          });

          // 页面路径处理（保持原逻辑）
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          const path = currentPage.route;
          const options = currentPage.options;

          const params = [];
          for (const key in options) {
            params.push(`${key}=${encodeURIComponent(options[key])}`);
          }
          const returnUrl = `/${path}${params.length ? '?' + params.join('&') : ''}`;

          // 存储跳转信息
          wx.setStorageSync('returnUrl', {
            path: returnUrl,
            isTab: ['pages/index/index', 'pages/my/my', 'pages/map/map'].includes(path)
          });

          // 第四步：延迟跳转（保证提示可见）
          setTimeout(() => {
            wx.hideLoading();
            wx.switchTab({ url: '/pages/my/my' });
          }, 1500); // 控制加载提示持续时间

        }, 2500); // 等待toast显示完成
        return;    
       
      }
   
    try {
      wx.showLoading({ title: '处理中...', mask: true })
      
      // 直接调用独立事务云函数
      const { result } = await wx.cloud.callFunction({
        name: 'saveCollectList',  // 需要新建的云函数
        data: {
          action: this.data.data.islike ? 'unfollow' : 'follow',
          poiId: this.data.id,
          poiData: {
            name: this.data.data.name,
            photo: this.data.data.photos?.[0]?.url || 'cloud://dp-6gydzcp27ac11774.6470-dp-6gydzcp27ac11774-1325695033/默认图片/NB-Map.png',
            type:'map',
          }
        }
      })
  
      if (result.code === 0) {
        this.setData({
          'data.islike': !this.data.data.islike
        }, () => {
          wx.showToast({
            title: this.data.data.islike ? '已收藏' : '已取消',
            icon: 'success'
          })
        })
      } else {
        throw new Error(result.msg)
      }
      
    } catch (err) {
      console.error('操作失败:', err)
      wx.showToast({ title: err.message || '操作失败', icon: 'none' })
    } finally {
      wx.hideLoading()
    }
  }


});